package com.sh.caryr.erp.controller.basis;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.sh.caryr.erp.entity.product.ProductSpec;
import com.sh.caryr.erp.entity.trade.Order;
import com.sh.caryr.erp.entity.user.User;
import com.sh.caryr.erp.excel.ExportToExcel;
import com.sh.caryr.erp.service.IProductSpecService;
import com.sh.caryr.erp.service.IOrderService;
import com.sh.caryr.erp.util.UtilityTool;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by milk on 2018/1/6.
 */

@Controller
@SessionAttributes("user")
@RequestMapping("/api/download")
public class DownloadController {

    @Autowired
    private IProductSpecService productSpecService;
    @Autowired
    private IOrderService orderService;

    @RequestMapping(value = "/template" ,method = RequestMethod.GET)
    public ResponseEntity<byte[]> downloadTemplate(HttpServletRequest request,
                                                   @RequestParam("filename") String filename,
                                                   @ModelAttribute("user") User operator) throws Exception {
        //查询数据
        List<ProductSpec> productSpecList = productSpecService.selectList(
                new EntityWrapper<ProductSpec>().eq("coco", operator.getCoco()));

        //通过模版生成文件
        String desPath = request.getServletContext().getRealPath("/resources/download/");
        ExportToExcel.exportTemplates(new ArrayList<Order>(), productSpecList,
                request.getServletContext().getRealPath("/resources/download/template" + File.separator + filename),
                desPath, filename);

        //下载文件路径
        return this.download(desPath, filename);

    }

    @RequestMapping(value = "/trades//{ids}" ,method = RequestMethod.GET)
    public ResponseEntity<byte[]> downloadTrades(HttpServletRequest request, @PathVariable String ids,
                                                   @ModelAttribute("user") User operator) throws Exception {
        //查询数据
        List<Long> list = UtilityTool.convertStringArray2LongList(ids.split(","));
        List<Order> orders = orderService.getOrderDetailByIds(list);
        List<ProductSpec> productSpecList = productSpecService.selectList(
                new EntityWrapper<ProductSpec>().eq("coco", operator.getCoco()));

        //生成文件
        String path = request.getServletContext().getRealPath("/resources/download/");
        String filename = "trade_order_data.xlsx";
        ExportToExcel.exportTemplates(orders, productSpecList,
                request.getServletContext().getRealPath("/resources/download/template" + File.separator + filename),
                path, filename);

        //下载文件路径
        return this.download(path, filename);

    }

    public ResponseEntity<byte[]> download(String path, String filename) throws Exception{
        //String path = request.getServletContext().getRealPath("/resources/download/");
        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);

    }

}
